package com.lq.demo.demo.mode.threadpool;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

public class DefaultThreadPool<Job extends Runnable> implements ThreadPool<Job> {
    private static final int MAX_POOL_NUM = 30;
    private static final int MAX_WORKER_NUM = 10;
    private static final int MIN_WORKER_NUM = 1;
    private static final int DEFAULT_WORKER_NUM = 4;
    private final LinkedList<Job> jobs = new LinkedList<>();
    // 工作者线程的列表
    private final List<Worker> workers = Collections.synchronizedList(new ArrayList<Worker>());
    private volatile int workNum;

    public static void main(String[] args) throws InterruptedException {
        DefaultThreadPool myPool = new DefaultThreadPool(8);

        for (int i = 0; i < 100; i++) {
            myPool.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName());
                }
            });
        }
        System.out.println(myPool.getWorkThreadSize());
        myPool.shutdown();
    }

    public DefaultThreadPool() {
        workNum = DEFAULT_WORKER_NUM;
        initWorkers(workNum);
    }

    public DefaultThreadPool(int num) {
        if (num <= 0) workNum = DEFAULT_WORKER_NUM;

        if (num > MAX_WORKER_NUM)
            workNum = MAX_WORKER_NUM;
        else
            workNum = num;

        initWorkers(workNum);
    }

    private void initWorkers(int workNum) {
        for (int i = 0; i < workNum; i++) {
            Worker worker = new Worker();
            workers.add(worker);
            Thread thread = new Thread(worker);
            thread.start();

        }
    }


    @Override
    public void execute(Job job) {
        if (job == null) return;

        synchronized (jobs) {
            if (jobs.size() >= MAX_POOL_NUM) {
                try {
                    jobs.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    Thread.currentThread().interrupt();
                    return;
                }
            }
            jobs.addLast(job);
            jobs.notify();
        }

    }

    @Override
    public void shutdown() {
        for (Worker worker : workers) {
            if (worker != null) {
                worker.shutDown();
            }
        }
    }

    @Override
    public int getWorkThreadSize() {
        return workers.size();
    }

    @Override
    public void addWorkers(int num) {
        synchronized (jobs) {
            if (num + workNum > MAX_WORKER_NUM) {
                num = MAX_WORKER_NUM - this.workNum;
            }
            initWorkers(num);
            this.workNum += num;
        }
    }

    @Override
    public void removeWorker(int num) {
        synchronized (jobs) {
            if (num > this.workNum) {
                throw new IllegalArgumentException("超过了已有的线程数量");
            }
            for (int i = 0; i < num; i++) {
                Worker worker = workers.get(i);
                if (worker != null) {
                    worker.shutDown();
                    workers.remove(i);
                }
            }
            this.workNum -= num;
        }


    }

    class Worker implements Runnable {
        private volatile boolean running = true;

        @Override
        public void run() {
            while (running) {
                Job job = null;
                synchronized (jobs) {
                    if (jobs.isEmpty()) {
                        try {
                            jobs.wait();
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                            System.out.println(Thread.currentThread().getName() + "被中止了");
                            return;
                        }
                    }
                    if (jobs.size() > 0)
                        job = jobs.removeFirst();
                    jobs.notify();

                }
                if (job != null) {
                    job.run();
                }
            }

        }


        public void shutDown() {
            running = false;
        }
    }

}
